package com.service.store;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.excel.EasyExcel;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.common.model.Global;
import com.common.spring.SpringMvcUtils;
import com.dao.pi.StoreDao;
import com.dao.store.MergeDao;
import com.model.pi.StoreModel;
import com.model.store.MergeModel;
import com.model.sys.SysUser;
import com.service.external.mes.MesStoreService;

@Service
public class MergeService {
	static final Logger logger = LoggerFactory.getLogger(MergeService.class);

	@Autowired
	MergeDao mergeDao;
	@Autowired
	StoreDao piStoreDao;
	@Autowired
	MesStoreService mesStoreService;

	public HttpResult selectMergeList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		List<MergeModel> list = mergeDao.selectList(queryMap);
		String tandString = list.stream().map(MergeModel::getMesTankNum).collect(Collectors.joining("','", "'", "'"));
		List<StoreModel> piList = piStoreDao.selectList(null);
		List<Object[]> mesList = (List<Object[]>) mesStoreService.getStore(tandString).getData();

		for (MergeModel mergeModel : list) {
			for (StoreModel storeModel : piList) {
				if (storeModel.getTankNum().equals(mergeModel.getPiTankNum())) {
					mergeModel.setStoHight(storeModel.getHeightLimit());
					mergeModel.setStoLow(storeModel.getLowLimit());
					mergeModel.setUpdateTime(storeModel.getUpdateTime());
					mergeModel.setStoNum(storeModel.getCurStore());
				}
			}

			for (Object[] objects : mesList) {
				if (objects[3].toString().equals(mergeModel.getMesTankNum())) {
					mergeModel.setStoHight(new BigDecimal(objects[6].toString()));
					mergeModel.setStoLow(new BigDecimal(objects[7].toString()));
					mergeModel.setUpdateTime(objects[8].toString());
					mergeModel.setStoNum(new BigDecimal(objects[9].toString()));
				}
			}
		}
		httpResult.setRows(list);
		httpResult.setTotal(list.size());
		logger.info("selectMergeList:{}", list);
		return httpResult;
	}

	/**
	 * 列表查询
	 *
	 * @param queryMap
	 * @return
	 */
	public HttpResult selectList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (StringUtils.isNotNull(sysUser.getDatapermission())) {
				queryMap.put("deptIds", sysUser.getDatapermission().split(","));
			} else {
				queryMap.put("createId", sysUser.getUserid());
			}
		}
		List<MergeModel> list = mergeDao.selectList(queryMap);
		int count = mergeDao.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectList:{}", list);
		return httpResult;
	}

	/**
	 * 返回数据字典格式
	 * @param queryMap
	 * @return
	 */
	public List<MergeModel> selectDicList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		List<MergeModel> list = mergeDao.selectList(queryMap);
		logger.info("selectList:{}", list);
		return list;
	}

	/**
	 * 详情
	 * 
	 * @param
	 * @return
	 */
	public HttpResult selectInfor(String facCode, String tankNum) {
		HttpResult httpResult = new HttpResult();
		MergeModel mergeModel = mergeDao.load(facCode, tankNum);
		httpResult.setData(mergeModel);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	/**
	 * 保存
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult save(MergeModel mergeModel) {
		if (mergeModel == null) {
			return HttpResult.error("参数不能为空");
		}
		HttpResult httpResult = new HttpResult();
		int result = 0;
		if (!StringUtils.isNotNull(mergeModel.getFacCode())) {
			mergeModel.setFacCode(UUID.randomUUID().toString());
			result = mergeDao.insert(mergeModel);
		} else {
			result = mergeDao.update(mergeModel);
		}
		if (!StringUtils.isNotNull(mergeModel.getTankNum())) {
			mergeModel.setTankNum(UUID.randomUUID().toString());
			result = mergeDao.insert(mergeModel);
		} else {
			result = mergeDao.update(mergeModel);
		}
		if (result > 0) {
			httpResult.setMsg(mergeModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(mergeModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(mergeModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	/**
	 * 提交
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult commit(MergeModel mergeModel) {
		if (mergeModel == null) {
			return HttpResult.error("参数不能为空");
		}
		mergeModel.setStatus(Global.YES + "");
		HttpResult httpResult = new HttpResult();
		int result = 0;
		result = mergeDao.update(mergeModel);
		result = mergeDao.update(mergeModel);
		if (result > 0) {
			httpResult.setMsg(mergeModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(mergeModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(mergeModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	/**
	 * 删除
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult delete(String facCode, String tankNum) {
		if (!StringUtils.isNotNull(facCode) || !StringUtils.isNotNull(tankNum)) {
			return HttpResult.error("参数不能为空");
		}
		MergeModel model = mergeDao.load(facCode, tankNum);
		if (model == null) {
			return HttpResult.error("无数据！");
		}
		if (!model.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("非待提交状态，不可删除！");
		}
		HttpResult httpResult = new HttpResult();
		int result = mergeDao.delete(facCode, tankNum);
		if (result > 0) {
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 撤回
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult back(String facCode, String tankNum) {
		if (!StringUtils.isNotNull(facCode) || !StringUtils.isNotNull(tankNum)) {
			return HttpResult.error("参数不能为空");
		}
		MergeModel model = mergeDao.load(facCode, tankNum);

		// todo

		HttpResult httpResult = new HttpResult();
		model.setStatus(Global.NO + "");
		int result = mergeDao.update(model);
		if (result > 0) {
			httpResult.setMsg("撤回成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 导出
	 * 
	 * @param queryMap
	 * @param response
	 */
	public void export(Map<String, Object> queryMap, HttpServletResponse response) {
		List<MergeModel> list = mergeDao.selectList(queryMap);
		logger.info("export:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), MergeModel.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}
}
